
<template>
  <el-card ref="wrapper" :body-style="{ padding: 0 }">
    <v-stage
      :config="stageConfig"
      @mousedown="mousedownHandler"
      @mouseup="mouseupHandler"
      @mousemove="mousemoveHandler"
    >
     <v-layer>
      <v-line v-for="(line,index) in lines" :key="index" :config="line" />

    </v-layer>
    </v-stage>
    
  </el-card>
</template>

<script>
import {mapGetters, mapState} from 'vuex'
export default {
  data() {
    return {
      // 画布配置
      stageConfig: {
        width: 800,
        height: 700
      },
      // 绘画状态
      painting: false,
     stroke: '#ff0000',
      strokeWidth: 5
    }
  },

  mounted() {
    // 将画布宽度设置与容器同宽
    this.stageConfig.width = this.$refs.wrapper.$el.offsetWidth
  },
  computed:{
    ...mapState(['lines']),
    ...mapGetters(['isGameStarted','isGameHolder'])
  },

  methods: {
    // 鼠标按下
    mousedownHandler(e) {
      console.log('鼠标按下了')


      //判断只有主持人才可以绘画
      if(!this.isGameStarted || !this.isGameHolder)return

      this.painting = true

      //创建一个新线条
      const nweLine={
        stroke:this.stroke,
        strokeWidth:this.strokeWidth,
        points:[e.evt.layerX,e.evt.layerY]
      }
      //本低画线，存储到vuex
      this.$store.commit('drawNewLine',nweLine)

      //请求服务器画新线
      this.$store.dispatch('updateNewLine',nweLine)
    },

    // 鼠标拖动
    mousemoveHandler(e) {
      if (this.painting) {
        console.log('鼠标拖动了, 绘画状态')
        const lastLine = this.lines[this.lines.length - 1]
        lastLine.points = lastLine.points.concat([e.evt.layerX,e.evt.layerY])
        this.$store.commit('updateNewLine',lastLine)

      //请求服务器同步线更新
      this.$store.dispatch('sendUpdateNewLine',lastLine)

      }
    },

    // 鼠标释放
    mouseupHandler() {
      console.log('鼠标释放了')
      this.painting = false
    }
  }
}
</script>